/**
 * Notes: 知识库管理控制器
 * Date: 2023-10-25 07:48:00
 */

const BaseProjectController = require('./base_project_controller.js');
const KnowledgeModel = require('../model/knowledge_model.js');
const BaiduCloud = require('../../../framework/cloud/baidu_cloud.js');
const timeUtil = require('../../../framework/utils/time_util.js');

class KnowledgeController extends BaseProjectController {
    /**
     * 列出知识库内容
     */
    async list() {
        // 获取分页参数
        const page = this.getParameter('page', 1);
        const size = this.getParameter('size', 20);
        const search = this.getParameter('search', '');
        
        // 检查用户是否为管理员
        await this.isAdmin();
        
        // 构建查询条件
        let where = {};
        if (search) {
            where.KNOWLEDGE_TITLE = {
                $regex: search,
                $options: 'i'
            }
        }
        
        // 查询数据
        let orderBy = {
            KNOWLEDGE_ADD_TIME: 'desc'
        };
        
        const result = await KnowledgeModel.getList(where, orderBy, page, size);
        
        // 格式化时间
        if (result && result.list) {
            result.list.forEach(item => {
                item.KNOWLEDGE_ADD_TIME_DESC = timeUtil.timestamp2Time(item.KNOWLEDGE_ADD_TIME, 'Y-M-D h:m');
                item.KNOWLEDGE_EDIT_TIME_DESC = timeUtil.timestamp2Time(item.KNOWLEDGE_EDIT_TIME, 'Y-M-D h:m');
                // 判断是否已向量化
                item.IS_VECTORIZED = item.KNOWLEDGE_VECTOR ? true : false;
            });
        }
        
        return this.success(result);
    }
    
    /**
     * 获取单个知识条目
     */
    async detail() {
        const id = this.getParameter('id');
        
        if (!id) {
            return this.error('知识库ID不能为空');
        }
        
        // 检查用户是否为管理员
        await this.isAdmin();
        
        const knowledge = await KnowledgeModel.getOne(id);
        
        if (knowledge) {
            // 格式化时间
            knowledge.KNOWLEDGE_ADD_TIME_DESC = timeUtil.timestamp2Time(knowledge.KNOWLEDGE_ADD_TIME, 'Y-M-D h:m');
            knowledge.KNOWLEDGE_EDIT_TIME_DESC = timeUtil.timestamp2Time(knowledge.KNOWLEDGE_EDIT_TIME, 'Y-M-D h:m');
            // 判断是否已向量化
            knowledge.IS_VECTORIZED = knowledge.KNOWLEDGE_VECTOR ? true : false;
        }
        
        return this.success(knowledge);
    }
    
    /**
     * 添加知识条目
     */
    async add() {
        // 获取参数
        const title = this.getParameter('title');
        const content = this.getParameter('content');
        
        if (!title || !content) {
            return this.error('标题和内容不能为空');
        }
        
        // 检查用户是否为管理员
        await this.isAdmin();
        
        // 准备数据
        const data = {
            KNOWLEDGE_TITLE: title,
            KNOWLEDGE_CONTENT: content,
            KNOWLEDGE_STATUS: KnowledgeModel.STATUS.SHOW,
            KNOWLEDGE_VECTOR_STATUS: KnowledgeModel.VECTOR_STATUS.PENDING
        };
        
        // 添加数据
        const id = await KnowledgeModel.insert(data);
        
        // 异步生成向量
        this.generateVector(id, title, content).catch(err => {
            console.error('向量化知识失败:', err);
        });
        
        return this.success({ id });
    }
    
    /**
     * 编辑知识条目
     */
    async edit() {
        // 获取参数
        const id = this.getParameter('id');
        const title = this.getParameter('title');
        const content = this.getParameter('content');
        const status = this.getParameter('status');
        
        if (!id) {
            return this.error('知识库ID不能为空');
        }
        
        if (!title || !content) {
            return this.error('标题和内容不能为空');
        }
        
        // 检查用户是否为管理员
        await this.isAdmin();
        
        // 准备更新数据
        const data = {
            KNOWLEDGE_TITLE: title,
            KNOWLEDGE_CONTENT: content,
            KNOWLEDGE_EDIT_TIME: timeUtil.time()
        };
        
        // 如果有状态参数，更新状态
        if (status !== undefined) {
            data.KNOWLEDGE_STATUS = status;
        }
        
        // 内容变更需要重新向量化
        data.KNOWLEDGE_VECTOR_STATUS = KnowledgeModel.VECTOR_STATUS.PENDING;
        
        // 更新数据
        await KnowledgeModel.edit(id, data);
        
        // 异步生成向量
        this.generateVector(id, title, content).catch(err => {
            console.error('向量化知识失败:', err);
        });
        
        return this.success(true);
    }
    
    /**
     * 删除知识条目
     */
    async delete() {
        const id = this.getParameter('id');
        
        if (!id) {
            return this.error('知识库ID不能为空');
        }
        
        // 检查用户是否为管理员
        await this.isAdmin();
        
        // 删除数据
        await KnowledgeModel.del(id);
        
        return this.success(true);
    }
    
    /**
     * 生成知识向量
     */
    async vectorize() {
        const id = this.getParameter('id');
        
        if (!id) {
            return this.error('知识库ID不能为空');
        }
        
        // 检查用户是否为管理员
        await this.isAdmin();
        
        // 获取知识条目
        const knowledge = await KnowledgeModel.getOne(id);
        
        if (!knowledge) {
            return this.error('知识条目不存在');
        }
        
        // 更新向量化状态为处理中
        await KnowledgeModel.edit(id, {
            KNOWLEDGE_VECTOR_STATUS: KnowledgeModel.VECTOR_STATUS.PROCESSING
        });
        
        try {
            // 生成向量
            const result = await this.generateVector(
                id, 
                knowledge.KNOWLEDGE_TITLE, 
                knowledge.KNOWLEDGE_CONTENT
            );
            
            return this.success(result);
        } catch (error) {
            console.error('向量化失败:', error);
            
            // 更新状态为失败
            await KnowledgeModel.edit(id, {
                KNOWLEDGE_VECTOR_STATUS: KnowledgeModel.VECTOR_STATUS.FAILED
            });
            
            return this.error('向量化失败: ' + error.message);
        }
    }
    
    /**
     * 批量向量化处理
     */
    async batchVectorize() {
        // 检查用户是否为管理员
        await this.isAdmin();
        
        // 获取待处理的知识条目
        const where = {
            KNOWLEDGE_VECTOR_STATUS: KnowledgeModel.VECTOR_STATUS.PENDING
        };
        
        const list = await KnowledgeModel.getAll(where);
        
        if (!list || list.length === 0) {
            return this.success({ count: 0, message: '没有需要向量化的知识条目' });
        }
        
        // 批量处理，最多处理10条
        const batch = list.slice(0, 10);
        const results = [];
        
        for (const item of batch) {
            try {
                // 更新状态为处理中
                await KnowledgeModel.edit(item._id, {
                    KNOWLEDGE_VECTOR_STATUS: KnowledgeModel.VECTOR_STATUS.PROCESSING
                });
                
                // 处理向量化
                await this.generateVector(
                    item._id,
                    item.KNOWLEDGE_TITLE,
                    item.KNOWLEDGE_CONTENT
                );
                
                results.push({
                    id: item._id,
                    title: item.KNOWLEDGE_TITLE,
                    result: 'success'
                });
            } catch (error) {
                console.error(`向量化失败 [${item._id}]:`, error);
                
                // 更新状态为失败
                await KnowledgeModel.edit(item._id, {
                    KNOWLEDGE_VECTOR_STATUS: KnowledgeModel.VECTOR_STATUS.FAILED
                });
                
                results.push({
                    id: item._id,
                    title: item.KNOWLEDGE_TITLE,
                    result: 'failed',
                    error: error.message
                });
            }
        }
        
        return this.success({
            count: batch.length,
            processed: results
        });
    }
    
    /**
     * 生成知识向量的具体实现
     * @private
     */
    async generateVector(id, title, content) {
        try {
            // 更新状态为处理中
            await KnowledgeModel.edit(id, {
                KNOWLEDGE_VECTOR_STATUS: KnowledgeModel.VECTOR_STATUS.PROCESSING
            });
            
            // 组合标题和内容
            const text = `标题: ${title}\n内容: ${content}`;
            
            // 调用百度API获取向量
            const vector = await BaiduCloud.getEmbedding(text);
            
            if (!vector) {
                throw new Error('向量生成失败');
            }
            
            // 更新向量和状态
            await KnowledgeModel.edit(id, {
                KNOWLEDGE_VECTOR: vector,
                KNOWLEDGE_VECTOR_STATUS: KnowledgeModel.VECTOR_STATUS.DONE
            });
            
            return {
                id,
                vectorSize: vector.length,
                status: 'success'
            };
        } catch (error) {
            // 更新状态为失败
            await KnowledgeModel.edit(id, {
                KNOWLEDGE_VECTOR_STATUS: KnowledgeModel.VECTOR_STATUS.FAILED
            });
            
            throw error;
        }
    }
}

module.exports = KnowledgeController; 